package com.skyline.search.config;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import com.skyline.search.util.SearchUtil;

/**
 * Class <code>Config</code> 通过Config类来对skyline-search进行配置
 * 
 * @author Jairus Chan
 * @version 0.1, 11/30/10
 * @since 0.1
 */

public class Config {
	private static String properties = "com/skyline/search/config/config.properties";
	private static Map<String, ConfigItem> configProperties = new HashMap<String, ConfigItem>();
	private static Config config = null;

	/**
	 * getConfig() 单例，你们懂的
	 * 
	 * @param
	 * @return Config
	 */
	public static synchronized Config getConfig() {
		if (config == null) {
			config = new Config();
		}
		return config;
	}

	public Config() {
		config();
	}

	/**
	 * setProperties()方法用于对server端的配置指定配置文件
	 * 
	 * @param properties
	 *            表示配置文件的路径
	 * @return
	 */
	public static void setProperties(String properties) {
		Config.properties = properties;
	}

	/**
	 * config()用于对server端的配置，从properties中读取配置信息
	 * 
	 * @param
	 * @return
	 */
	public static void config() {
		URL sqlDir = Config.class.getClassLoader().getResource(properties);
		File file = new File(sqlDir.getPath().replace("%20", " "));
		InputStream is;
		try {
			is = new FileInputStream(file);
			Properties ps = new Properties();
			ps.load(is);
			is.close();
			Enumeration<Object> enums = ps.keys();
			while (enums.hasMoreElements()) {
				String indexKey = (String) enums.nextElement();
				String indexValue = ps.getProperty(indexKey);
				String[] indexValues = indexValue.split(";");
				ConfigItem configItem = new ConfigItem();
				configItem.setIndexpath(indexValues[0]);
				configItem.setBathdoc(new Integer(indexValues[1]));
				configProperties.put(indexKey, configItem);
				SearchUtil.makefile(indexValues[0]);
			}
			System.out.println("Congratirations:config successfully!");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * getConfigProperties() 获取server端的配置信息
	 * 
	 * @param
	 * @return Map<String, ConfigItem> String 为各个indexPath, ConfigItem
	 *         为这个indexPath的配置信息
	 */
	public static Map<String, ConfigItem> getConfigProperties() {
		return configProperties;
	}

}
